package com.zhaolang.qogir.ui.manage;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zhaolang.qogir.R;
import com.zhaolang.qogir.bean.ProductBean;
import com.zhaolang.qogir.bean.ProductClassBean;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.ReqFactory;
import com.zhaolang.qogir.domain.WaresManage;
import com.zhaolang.qogir.domain.WaresManage.UpdateShopResp;
import com.zhaolang.qogir.ui.BaseActivity;
import com.zhaolang.qogir.ui.ContextState;
import com.zhaolang.qogir.ui.TitleView;
import com.zhaolang.qogir.ui.adapter.manage.ManageClassSpinnerAdapter;
import com.zhaolang.qogir.ui.settings.DialogHeadChange;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.PhotoUtils;
import com.zhaolang.qogir.util.SettingsInfoUtil;
import com.zhaolang.qogir.util.Slog;
import com.zhaolang.qogir.util.ToastUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityManageAdd extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.manage_btn_img_add)
    TextView manageBtnImgAdd;
    @ViewInject(R.id.manage_product_price)
    EditText manageProductPrice;
    @ViewInject(R.id.manage_product_delivery)
    EditText manageProductDelivery;
    @ViewInject(R.id.manage_product_name)
    EditText manageProductName;
    @ViewInject(R.id.manage_product_des)
    EditText manageProductDes;
    @ViewInject(R.id.manage_product_stock)
    EditText manageProductStock;
    @ViewInject(R.id.manage_product_max_stock)
    EditText manageProductMaxStock;
    @ViewInject(R.id.manage_iv_img_show)
    ImageView manageIvImgShow;

    private TitleView mTitle;
    private Spinner spinner;
    /* max class num */
    private final int MAX_CLASS_NUM = 4;
    private String[] arr = new String[MAX_CLASS_NUM];
    private DialogHeadChange mHeadChangeDialog;

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private static final String STORE_HEAD = "qogir";
    private File fileUri = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;
    private static final int OUTPUT_X = 200;
    private static final int OUTPUT_Y = 200;
    private String classifyStr;
    private Context mContext;
    private WaresManage waresManage;
    private String thumbnail;
    private List<String> thumbnailList;
    private List<ProductClassBean> classList = new ArrayList<>();
    private ManageClassSpinnerAdapter spinnerAdapter;
    private WaresManage.ProductBeanReq productBeanReq;

    private BaseCall<UpdateShopResp> mThumbnailCallback = new BaseCall<UpdateShopResp>() {
        @Override
        public void call(UpdateShopResp resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                String thumbnailURL = resp.getThumbnailURL();
                Slog.d("update thumbnailURL success : "
                        + HttpConstant.OFFICIAL_USER_HOST_IP + thumbnailURL);
                thumbnail = HttpConstant.OFFICIAL_USER_HOST_IP + thumbnailURL;
                finish();
            } else {
                Slog.e("Failed update thumbnailURL!!!!!!!  " + resp.getMessage());
            }
        }
    };

    private BaseCall<WaresManage.ProductReq> mProductCallback = new BaseCall<WaresManage.ProductReq>() {
        @Override
        public void call(WaresManage.ProductReq resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                notifyUiDataChanged(resp.getProductBean());
            } else {
                Slog.e("Failed update mProductClassCallback!!!!!!!  " + resp.getMessage());
            }
        }
    };

    private BaseCall<WaresManage.ListProductClassBeanReq> mProductClassCallback = new BaseCall<WaresManage.ListProductClassBeanReq>() {
        @Override
        public void call(WaresManage.ListProductClassBeanReq resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                classList = resp.getProclassList();
                final List<String> ls = new ArrayList<>();
                for (int i = 0; i < classList.size(); i++) {
                    ProductClassBean classBean = classList.get(i);
                    ls.add(classBean.getProclassName());
                }
                if (spinnerAdapter != null) {
                    spinnerAdapter.setData(ls);
                    spinnerAdapter.notifyDataSetChanged();
                }
                /* select first item for first data line */
                classifyStr = spinnerAdapter.getItem(0);
                productBeanReq.setClassId(classList.get(0).getProclassClassid());
            } else {
                Slog.e("Failed update mProductClassCallback!!!!!!!  " + resp.getMessage());
            }
            dimessWaitingDialog();
        }
    };

    /**
     * update product details info
     */
    private BaseCall<WaresManage.UpdateShopResp> mUpdateProInfoCallback = new BaseCall<WaresManage.UpdateShopResp>() {
        @Override
        public void call(WaresManage.UpdateShopResp resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                Slog.d("update product info success");
                dimessWaitingDialog();
                String productId = resp.getProductId();
                Slog.d("huangwei, productId" + productId);
                //upload product thumbnail
                waresManage.updateWaresImageAsync(thumbnailList, productId, mThumbnailCallback);
            } else {
                ToastUtils.showShort(mContext, "添加失败");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_add);
        ViewUtils.inject(this);
        mContext = this;
        waresManage = ReqFactory.buildInterface(this,
                WaresManage.class);

        mHeadChangeDialog = new DialogHeadChange(this);
        mHeadChangeDialog.setButtonsOnClickListener(this, this, this);
        thumbnailList = new ArrayList<>();
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("Message");
        final String type = bundle.getString("type");
        if (type.equals("pro_edit")) {
            //TODO add page
            String product_id = bundle.getString("product_id");
            String class_id = bundle.getString("class_id");
            waresManage.getProductAsync(product_id, mProductCallback);
        }
        //ready for product entity
        productBeanReq = new WaresManage.ProductBeanReq();
        findView(type);
        addCallback(mUpdateProInfoCallback);
        addCallback(mThumbnailCallback);
    }

    @OnClick({R.id.manage_btn_img_add, R.id.manage_iv_img_show})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.manage_btn_img_add:
                mHeadChangeDialog.show();
                break;
            case R.id.manage_iv_img_show:
                mHeadChangeDialog.show();
                break;
            case DialogHeadChange.ID_PHOTO:
                mHeadChangeDialog.dismiss();
                autoObtainStoragePermission();
                break;
            case DialogHeadChange.ID_TAKIN:
                mHeadChangeDialog.dismiss();
                autoObtainCameraPermission();
                break;
            case DialogHeadChange.ID_CANCEL:
                mHeadChangeDialog.dismiss();
                break;
            case TitleView.ID_LEFT:
                finish();
                break;
            case TitleView.ID_RIGHT:
                handleProductSave();
                break;
            default:
        }
    }

    private void findView(String type) {
        View title = findViewById(R.id.vg_title);
        mTitle = new TitleView(this, title);
        if (type.equals("pro_add")) {
            manageBtnImgAdd.setVisibility(View.VISIBLE);
            mTitle.setCenterText(R.string.manage_product_add, null);
        } else if (type.equals("pro_edit")) {
            manageBtnImgAdd.setVisibility(View.GONE);
            manageIvImgShow.setVisibility(View.VISIBLE);
            mTitle.setCenterText(R.string.manage_product_edit, null);
        }
        mTitle.setLeftText(getString(R.string.ui_manage_string_cancel), null);
        mTitle.setRightText(getString(R.string.ui_manage_string_save), null);
        mTitle.setLeftText(R.string.ui_manage_string_cancel, this);
        mTitle.setRightText(R.string.ui_manage_string_save, this);
        spinner = findViewById(R.id.manage_class_spinner);
        spinnerAdapter = new ManageClassSpinnerAdapter(this);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                classifyStr = spinnerAdapter.getItem(position);
                for (int i = 0; i < classList.size(); i++) {
                    if (classList.get(i).getProclassName().equals(classifyStr)) {
                        productBeanReq.setClassId(classList.get(i).getProclassClassid());
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    private void handleProductSave() {
        showWaitingDialog((ContextState) null);
        if (TextUtils.isEmpty(manageProductName.getText()) ||
                TextUtils.isEmpty(manageProductPrice.getText()) ||
                TextUtils.isEmpty(classifyStr) || TextUtils.isEmpty(manageProductDes.getText()) ||
                TextUtils.isEmpty(manageProductDelivery.getText()) ||
                TextUtils.isEmpty(manageProductStock.getText()) ||
                TextUtils.isEmpty(manageProductMaxStock.getText())) {
            ToastUtils.showShort(this, "信息填写有误!");
            return;
        }

        productBeanReq.setName(manageProductName.getText().toString());
        productBeanReq.setDesc(manageProductDes.getText().toString());
        productBeanReq.setStock(manageProductStock.getText().toString());
        productBeanReq.setMaxStock(manageProductMaxStock.getText().toString());
        productBeanReq.setPrice(manageProductPrice.getText().toString());
        productBeanReq.setDelivery(manageProductDelivery.getText().toString());
        if (thumbnailList == null || thumbnailList.size() <= 0) {
            return;
        }
        //upload product details info
        waresManage.updateWaresRequirementsAsync(productBeanReq, mUpdateProInfoCallback);

    }

    /**
     * 动态申请sdcard读写权限
     */
    private void autoObtainStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
            } else {
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
            }
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }
    }

    /**
     * 申请访问相机权限
     */
    private void autoObtainCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    ToastUtils.showShort(this, "您已经拒绝过一次");
                }
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
            } else {//有权限直接调用系统相机拍照
                if (PhotoUtils.hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    //通过FileProvider创建一个content类型的Uri
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        imageUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", fileUri);
                    }
                    PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    ToastUtils.showShort(this, "设备没有SD卡！");
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Slog.d("onActivityResult: requestCode: " + requestCode + "  resultCode:" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            Slog.e("onActivityResult: resultCode!=RESULT_OK");
            return;
        }
        switch (requestCode) {
            //相机返回
            case CODE_CAMERA_REQUEST:
                cropImageUri = Uri.fromFile(fileCropUri);
                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                break;
            //相册返回
            case CODE_GALLERY_REQUEST:
                if (PhotoUtils.hasSdcard()) {
                    Slog.d("CODE_GALLERY_REQUEST request");
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", new File(newUri.getPath()));
                    }
                    Slog.d("start to crop image uri");
                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                } else {
                    ToastUtils.showShort(this, "设备没有SD卡！");
                }
                break;
            //裁剪返回
            case CODE_RESULT_REQUEST:
                Bitmap photo = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                if (photo != null) {
                    //enable product image show
                    manageBtnImgAdd.setVisibility(View.GONE);
                    manageIvImgShow.setVisibility(View.VISIBLE);
                    manageIvImgShow.setImageBitmap(photo);
                    Slog.w("update portrait : " + fileCropUri);
                    saveImage(photo, fileCropUri.getAbsolutePath());
                    thumbnailList.add(fileCropUri.getAbsolutePath());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Slog.d("onRequestPermissionsResult: ");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PhotoUtils.hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            //通过FileProvider创建一个content类型的Uri
                            imageUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", fileUri);
                        }
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtils.showShort(this, "设备没有SD卡！");
                    }
                } else {
                    ToastUtils.showShort(this, "请允许打开相机！！");
                }
                break;
            }
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    ToastUtils.showShort(this, "请允许打操作SDCard！！");
                }
                break;
            default:
        }
    }

    private boolean saveImage(Bitmap photo, String spath) {
        try {
            File file = new File(spath);
            File parant = file.getParentFile();
            if (!parant.exists()) {
                parant.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
//            file.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            Slog.e("", e);
            return false;
        }
        return true;
    }

    /**
     * update all view when wise to product edit function
     *
     * @param bean
     */
    private void notifyUiDataChanged(ProductBean bean){
        manageProductPrice.setText(bean.getPrice());
        manageProductName.setText(bean.getName());
        manageProductMaxStock.setText(bean.getMaxStock());
        /* delivery fee set to 1 default */
        manageProductDelivery.setText("1");
        manageProductDes.setText(bean.desc);
        manageProductStock.setText(bean.stock);
        String thumbnail = HttpConstant.DEBUG_USER_HOST_IP + bean.getThumbnail();
        SettingsInfoUtil.setImageFromUrl(thumbnail, manageIvImgShow);

    }

    @Override
    protected void onResume() {
        super.onResume();
        waresManage.getShopClassAsync(mProductClassCallback);
    }
}
